﻿using System;
using System.IO;
using System.Windows.Forms;
using EAI.Logging;
using Outlook = Microsoft.Office.Interop.Outlook;
using Office = Microsoft.Office.Core;

namespace EAI.Office
{
    public partial class ThisAddIn
    {
        private void ThisAddIn_Startup(object sender, System.EventArgs e)
        {
            InitializeToolBar();

            this.Application.NewMail += new Microsoft.Office.Interop.Outlook.ApplicationEvents_11_NewMailEventHandler(Application_NewMail);
        }

        private void Application_NewMail()
        {
            Outlook.Folder olFolderInbox = (Outlook.Folder)Application.GetNamespace("MAPI").GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox);
            MoveFolderMail(olFolderInbox, true);
        }

        private void ThisAddIn_Shutdown(object sender, System.EventArgs e)
        {
        }

        private void InitializeToolBar()
        {
            try
            {
                Office.CommandBars cmdBars = this.Application.ActiveExplorer().CommandBars;

                try
                {
                    Office.CommandBar commandBar = cmdBars["X TOOL"];
                }
                catch
                {
                    Office.CommandBar commandBar = cmdBars.Add("X TOOL", Office.MsoBarPosition.msoBarTop, false, true);
                    commandBar.Visible = true;

                    Office.CommandBarButton commandBarButtonImport = (Office.CommandBarButton)commandBar.Controls.Add(1, missing, missing, missing, true);
                    commandBarButtonImport.Style = Office.MsoButtonStyle.msoButtonCaption;
                    commandBarButtonImport.Caption = "&XImport";
                    commandBarButtonImport.Tag = "XImport";
                    commandBarButtonImport.Visible = true;
                    commandBarButtonImport.Click += new Microsoft.Office.Core._CommandBarButtonEvents_ClickEventHandler(CommandBarButton_Click);

                    Office.CommandBarButton commandBarButtonExport = (Office.CommandBarButton)commandBar.Controls.Add(1, missing, missing, missing, true);
                    commandBarButtonExport.Style = Office.MsoButtonStyle.msoButtonCaption;
                    commandBarButtonExport.Caption = "&XExport";
                    commandBarButtonExport.Tag = "XExport";
                    commandBarButtonExport.Visible = true;
                    commandBarButtonExport.Click += new Microsoft.Office.Core._CommandBarButtonEvents_ClickEventHandler(CommandBarButton_Click);

                    Office.CommandBarButton commandBarButtonFlush = (Office.CommandBarButton)commandBar.Controls.Add(1, missing, missing, missing, true);
                    commandBarButtonFlush.Style = Office.MsoButtonStyle.msoButtonCaption;
                    commandBarButtonFlush.Caption = "&XFlush";
                    commandBarButtonFlush.Tag = "XFlush";
                    commandBarButtonFlush.Visible = true;
                    commandBarButtonFlush.Click += new Microsoft.Office.Core._CommandBarButtonEvents_ClickEventHandler(CommandBarButton_Click);
                }
            }
            catch (Exception ex)
            {
                Log4NetHelper.GetLogger().LevelLog(EAILogLevel.Error, ex);
            }
        }

        private void CommandBarButton_Click(Microsoft.Office.Core.CommandBarButton Ctrl, ref bool CancelDefault)
        {
            switch (Ctrl.Tag)
            {
                case "XExport":
                    Export();
                    break;
                case "XFlush":
                    Outlook.Folder olFolderInbox = (Outlook.Folder)Application.GetNamespace("MAPI").GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox);
                    MoveFolderMail(olFolderInbox, false);
                    break;
                case "XImport":
                    Import();
                    break;
                default:
                    break;
            }
        }

        private void Export()
        {
            try
            {             
                OfficeConfig.Instance.PersistentConfig();

                using (FolderBrowserDialog dilog = new System.Windows.Forms.FolderBrowserDialog())
                {
                    switch (dilog.ShowDialog())
                    {
                        case DialogResult.OK:
                        case DialogResult.Yes:

                            File.Copy(OfficeConfig.OfficeConfigFile, Path.Combine(dilog.SelectedPath, OfficeConfig.OfficeConfigFile), true);
                            MessageBox.Show("Export successfully!");
                            break;
                    }
                }
            }
            catch (Exception ex)
            {
                Log4NetHelper.GetLogger().LevelLog(EAILogLevel.Error, ex);
            }
        }

        private void Import()
        {
            using (OpenFileDialog dilog = new System.Windows.Forms.OpenFileDialog())
            {
                dilog.Multiselect = false;
                switch (dilog.ShowDialog())
                {
                    case DialogResult.OK:
                    case DialogResult.Yes:

                        OfficeConfig.Instance.LoadConfig(dilog.FileName);
                        OfficeConfig.Instance.PersistentConfig();
                        MessageBox.Show("Import successfully!");
                        break;
                }
            }
        }

        private void MoveFolderMail(Outlook.Folder inbox, bool isUnread)
        {
            try
            {
                Outlook.Items unreadMailItems = isUnread ? inbox.Items.Restrict("[Unread]= true") : inbox.Items;

                Outlook.MailItem moveMail = null;

                foreach (object eMail in unreadMailItems)
                {
                    try
                    {
                        moveMail = eMail as Outlook.MailItem;
                        if (moveMail != null)
                        {
                            string senderEmailAddress = GetSenderSMTPAddress(moveMail);
                            senderEmailAddress = string.IsNullOrEmpty(senderEmailAddress) ? string.Empty : senderEmailAddress.ToLower();

                            if (!OfficeConfig.Instance.HashTable.ContainsKey(senderEmailAddress))
                            {
                                continue;
                            }

                            MailItem mailItem = OfficeConfig.Instance.HashTable[senderEmailAddress] as MailItem;
                            if (mailItem == null && string.IsNullOrEmpty(mailItem.Folder))
                            {
                                continue;
                            }

                            Outlook.Folder to = CheckOrCreateFolder(inbox, mailItem.Folder);

                            if (to != null)
                            {
                                moveMail.Move(to);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Log4NetHelper.GetLogger().LevelLog(EAILogLevel.Error, ex);
                    }
                }
            }
            catch (Exception ex)
            {
                Log4NetHelper.GetLogger().LevelLog(EAILogLevel.Error, ex);
            }
        }
      
        private Outlook.Folder CheckOrCreateFolder(Outlook.Folder inbox, string folder)
        {
            Outlook.Folder retVal = null;
            try
            {
                retVal = (Outlook.Folder)inbox.Folders[folder];
            }
            catch
            {
                retVal = (Outlook.Folder)inbox.Folders.Add(folder, missing);
            }

            return retVal;
        }

        private string GetSenderSMTPAddress(Outlook.MailItem mail)
        {
            string retVal = string.Empty;
            if (mail != null)
            {
                if (mail.SenderEmailType == "EX")
                {
                    Outlook.NameSpace mySpace = Application.GetNamespace("MAPI");

                    Outlook.Recipient recipient = mySpace.CreateRecipient(mail.SenderEmailAddress);

                    Outlook.ExchangeUser exUser = recipient.AddressEntry.GetExchangeUser();

                    retVal = exUser.PrimarySmtpAddress;
                }
                else
                {
                    retVal = mail.SenderEmailAddress;
                }
            }
            return retVal;
        }

        #region VSTO generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InternalStartup()
        {
            this.Startup += new System.EventHandler(ThisAddIn_Startup);
            this.Shutdown += new System.EventHandler(ThisAddIn_Shutdown);

        }

        #endregion
    }
}
